package snapex.core.security;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import lombok.extern.slf4j.Slf4j;
import snapex.ServerConfiguration;

@Slf4j
@Component
public class AuthenticationFilter extends ZuulFilter {

	@Autowired
	ServerConfiguration serverConfig;
	
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		String token = request.getHeader(HttpHeaders.AUTHORIZATION);
		
		boolean isTokenExpired = false;
		if(StringUtils.isEmpty(token)) {			
			token = request.getHeader("WechatAccessToken");
			
			if(StringUtils.isEmpty(token)) {
				token = request.getParameter("access_token");
			}
			
			if(!StringUtils.isEmpty(token)) {
				
				isTokenExpired = JwtUtils.isExpired(token);
				if(!isTokenExpired) {
					ctx.addZuulRequestHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
				}
			}
		}
		else {
			isTokenExpired = JwtUtils.isExpired(token.substring("Bearer ".length()));
		}
				      	            
        if(isTokenExpired){
    		ctx.setResponseStatusCode(HttpStatus.OK.value());
    		ctx.setSendZuulResponse(false); //stop forwarding request to downstream application
    		
    		ctx.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);	        		
    		ctx.setResponseBody("{\"code\":401,\"msg\":\"Access Defined: Token Expired!\"}");        		
        }
        
        ctx.getResponse().addHeader("x-snapex-gateway", serverConfig.getUrl());
        
//			     
//            if(JwtUtils.isExpired(token.substring("Bearer ".length()))){
//        		
//        		String redirectURL = "/authenticate";
//        		ctx.setSendZuulResponse(false);
//                ctx.put(FilterConstants.FORWARD_TO_KEY, redirectURL);
//                ctx.setResponseStatusCode(HttpStatus.TEMPORARY_REDIRECT.value());
//                try {
//                	ctx.getResponse().sendRedirect(redirectURL);
//                }catch(IOException e) {
//                	log.error("",e);
//                }
//            }
		
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
